<template>
  <div v-loading="loading" class="AddOrUpdate_main add_container column_two">
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="保养模板编码" prop="code">
          <CodeRuleInput :band-value.sync="formData.code" table-name="device_maintain_template" column-name="code" :is-edit="id" />
        </el-form-item>
        <el-form-item label="保养模板名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入" clearable />
        </el-form-item>

        <el-form-item label="备注" class="double">
          <el-input v-model="formData.remark" maxlength="200" show-word-limit type="textarea" placeholder="请输入" />
        </el-form-item>
        <el-form-item v-if="isShow" label="状态">
          <el-radio-group v-model="formData.status">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <div class="formItem_header">
        <div class="name">保养明细</div>
        <div class="formItem_header_operate">

          <a class="formItem_header_operate_item" @click="addRow">
            <svg-icon icon-class="新增" />
            <div class="item_name">添加</div>
          </a>
          <a class="formItem_header_operate_item" @click="importData">
            <svg-icon icon-class="导入" />
            <div class="item_name">导入</div>
          </a>
          <a v-if="formData.id" class="formItem_header_operate_item" @click="getExportData">
            <svg-icon icon-class="导出" />
            <div class="item_name">导出</div>
          </a>
          <a class="formItem_header_operate_item delete" @click="removeRow">
            <svg-icon icon-class="删除" />
            <div class="item_name">删除</div>
          </a>
        </div>
      </div>

      <div ref="table_container" class="table_container draggableTable addRow_table">
        <el-table
          ref="table"
          :data="tableData"
          :height="tableHeight"
          stripe
          border
          row-key="id"
          style="width: 99.9%"
          :cell-class-name="cellClassName"
          :header-cell-class-name="headerCellClassName"
          :row-class-name="rowClassName"
          @selection-change="selectionChange1"
        >
          <el-table-column type="selection" align="center" width="50" />
          <el-table-column
            prop="sort"
            label="序号"
            min-width="50"
          >
            <template slot-scope="scope">
              <div v-if="!scope.row.isAdd">{{ scope.row.sort }}</div>
              <div v-else />
            </template>
          </el-table-column>
          <el-table-column
            prop="name"
            label="保养项目"
            min-width="200"
          >
            <template slot-scope="scope">
              <el-input v-if="!scope.row.isAdd" v-model="scope.row.name" type="textarea" placeholder="请输入" />
              <div v-else />
            </template>
          </el-table-column>
          <el-table-column
            prop="content"
            label="保养内容"
            min-width="200"
          >
            <template slot-scope="scope">
              <el-input v-if="!scope.row.isAdd" v-model="scope.row.content" type="textarea" placeholder="请输入" />
              <div v-else />
            </template>
          </el-table-column>
          <el-table-column
            prop="way"
            label="保养方式"
            min-width="200"
          >
            <template slot-scope="scope">
              <el-input v-if="!scope.row.isAdd" v-model="scope.row.way" type="textarea" placeholder="请输入" />
              <div v-else />
            </template>
          </el-table-column>
          <el-table-column
            prop="time"
            label="时间 ( S )"
            min-width="100"
          >
            <template slot-scope="scope">
              <el-input v-if="!scope.row.isAdd" v-model="scope.row.time" type="textarea" onkeyup="if(isNaN(value))execCommand('undo')" onafterpaste="if(isNaN(value))execCommand('undo')" placeholder="请输入" />
              <div v-else />
            </template>
          </el-table-column>
          <el-table-column
            prop="criterion"
            label="判断标准"
            min-width="200"
          >
            <template slot-scope="scope">
              <el-input v-if="!scope.row.isAdd" v-model="scope.row.criterion" type="textarea" placeholder="请输入" />
              <div v-else />
            </template>
          </el-table-column>
          <el-table-column
            label="至少上传张数"
            min-width="120"
          >
            <template slot-scope="scope">
              <el-input v-if="!scope.row.isAdd" v-model="scope.row.minPage" type="textarea" placeholder="请输入" />
              <div v-else />
            </template>
          </el-table-column>
          <el-table-column
            label="附件"
            min-width="150"
          >
            <template slot-scope="scope">
              <FileManage
                v-if="!scope.row.isAdd"
                :file-names.sync="scope.row.fileName"
                :file-real-names.sync="scope.row.fileRealName"
                :file-urls.sync="scope.row.fileUrl"
                :row-index="scope.$index"
                @fileName="setFileName"
              />
              <div v-else />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="onSubmit">保存</el-button>
    </div>
  </div>
</template>

<script>
import { addOrUpdate, getInfo, importMethod } from '@/api/equipmentManage/equipmentMaintain/maintainTemplate'
import Sortable from 'sortablejs'
import ImportData from '@/components/JLink/common/ImportData'
import { export2Excel } from '@/utils/util'
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {}
  },
  data() {
    return {
      loading: true,
      isShow: false,
      formData: {
        code: '',
        name: '',
        remark: '',
        status: '1'
      },
      rules: {
        code: [
          { required: true, message: '保养模板编码不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '保养模板名称不能为空', trigger: 'change' }
        ]
      },
      tableColumn: [
        { prop: 'name', label: '保养项目' },
        { prop: 'content', label: '保养内容' },
        { prop: 'way', label: '保养方式' },
        { prop: 'time', label: '时间 ( S )' },
        { prop: 'criterion', label: '判断标准' }
      ],
      pageId: '保养明细',
      tableHeight: '360',
      selectionsAll1: [],
      tableData: []
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.tableHeight = this.$refs.table_container[0].offsetHeight
    })
    if (!this.id) { // 没有id就是新增
      this.loading = false
      this.addRow({})
    } else { // 有id就是编辑
      this.formData.id = this.id
      this.getById()
      setTimeout(() => {
        this.rowDrop()
      }, 50)
    }
  },
  methods: {// 表格拖动排序

    headerCellClassName(data) {
      if (['name', 'content'].indexOf(data.column.property) != -1) {
        return 'column_bt'
      }
    },
    selectionChange1(rows) {
      this.selectionsAll1 = rows
    },
    rowDrop() {
      // 此时找到的元素是要拖拽元素的父容器
      const tbody = document.querySelector('.draggableTable')
        .querySelector('.el-table__body-wrapper').querySelector('tbody')
      const _this = this
      Sortable.create(tbody, {
        draggable: '.normalRow',
        filter: '.el-input__inner', // Selectors that do not lead to dragging (String or Function)
        preventOnFilter: false, // Call `event.preventDefault()` when triggered `filter`
        onEnd({ newIndex, oldIndex }) {
          const cacheData1 = _this.$deepClone(_this.tableData[oldIndex])
          const cacheData2 = _this.$deepClone(_this.tableData[newIndex])
          const cacheTableData = _this.$deepClone(_this.tableData)
          cacheTableData[newIndex] = cacheData1
          cacheTableData[oldIndex] = cacheData2
          _this.reSortTable(cacheTableData)
        }
      })
    },
    reSortTable(tableData) { // 对表格重新排序
      tableData.forEach((item, index) => {
        if (!item.isAdd) {
          item.sort = index + 1
        }
      })
      this.tableData = []
      setTimeout(() => { // 加延时重置表格
        this.tableData = tableData
      }, 50)
    },
    getExportData() {
      export2Excel(this.tableColumn, this.tableData, this.pageId)
    },
    importData() { // 导入
      this.$layer.iframe({// 弹框
        content: {
          content: ImportData, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {}// props
        },
        area: ['440px', '250px'],
        title: '导入数据', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    importMethod(files) { // 导入接口
      importMethod(files).then(res => {
        if (res.data) {
          this.tableData = []
          res.data.forEach(item => {
            this.addRow(item)
          })
        }
      })
    },
    addRow(row) {
      const row2 = [
        {
          sort: this.tableData.length + 1,
          name: row.name || '',
          content: row.content || '',
          way: row.way || '',
          time: row.time || '',
          criterion: row.criterion || '',
          fileName: row.fileName || '',
          fileRealName: row.fileRealName || '',
          fileUrl: row.fileUrl || ''
        }
      ]
      this.tableData.push(...row2)
      setTimeout(() => {
        this.rowDrop()
      }, 50)
    },
    removeRow(row) {
      this.selectionsAll1.forEach(item => {
        this.tableData.splice(this.tableData.indexOf(item), 1)
      })
      this.reSortTable(this.tableData)
    },
    cellClassName(data) {
      if (data.column.property == 'operate') {
        if (data.rowIndex % 2 == 0) { // 单数行
          return 'fixed one'
        } else { // 双数行
          return 'fixed two'
        }
      }
    },
    rowClassName({ row, rowIndex }) {
      if (rowIndex == this.tableData.length - 1 && row.isAdd) {
        return 'addRow'
      } else {
        return 'normalRow'
      }
    },
    getById() {
      getInfo(this.id).then(res => {
        Object.keys(this.formData).forEach(key => { // 给右边数据赋值
          this.formData[key] = res.data[key]
        })
        this.isShow = true
        this.loading = false
        this.tableData = res.data.itemList
        this.formData.status += ''
        // this.tableData.push({ isAdd: true })
      })
    },
    onSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          const tableData = JSON.parse(JSON.stringify(this.tableData))
          if (this.tableData.length > 0) {
            if ((tableData[tableData.length - 1]).isAdd) {
              tableData.splice(tableData.length - 1, 1)
            }
          }
          if (tableData.some(item => !item.content)) {
            this.$message.warning('请添加保养内容')
            return false
          } else if (tableData.some(item => !item.name) || tableData.length == 0) {
            this.$message.warning('请添加保养项目')
            return false
          } else if (tableData.filter(item => item.time && !this.SETTINGS.reg_integer.test(item.time)).length > 0) {
            this.$message.warning('时间未正确填写')
            return false
          } else if (tableData.filter(item => item.minPage && !this.SETTINGS.reg_integer.test(item.minPage)).length > 0) {
            this.$message.warning('至少上传张数未正常填写')
            return false
          } else {
            this.formData.itemList = tableData
            addOrUpdate(this.formData).then(res => {
              this.$message({
                message: res.msg,
                type: 'success'
              })
              this.$layer.close(this.layerid) // 关闭弹框
              this.$parent.getList() // 调用父组件的刷新方法
            })
          }
        }
      })
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    },
    setFileName(...data) {
      this.tableData[data[3]].fileName = data[0]
      this.tableData[data[3]].fileRealName = data[1]
      this.tableData[data[3]].fileUrl = data[2]
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .el-table__row{
  height: 80px;
}
.table_container{
  /deep/ .el-input__inner{
    min-height: 54px !important;
  }
}
.main_main{
    .formItem_header{
    justify-content: space-between;
    align-items: center;
    height: 40px;
    margin-top:-10px ;
     margin-bottom:10px ;
  }
}
</style>
